﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//using System.Data;
using System.Data.SqlClient;
using System.Globalization;

using CNCSoft.EWinform;
using CNCSoft.EWinform.ControlUtils;
using CNCSoft.EWinform.AGrid;
using CNCSoft.EData;

using DevExpress.XtraGrid;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Base;

using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System.Threading;
using Common;

namespace CNCSoft.ErpApps.TMS
{
    public partial class frmNhapDiem : Form
    {
        private BindingSource bindingSource1 = new BindingSource();
        private BindingSource bindingSource_DiemChu = new BindingSource();
        private SqlDataAdapter dataAdapter = new SqlDataAdapter();
        DataGridStyleFactory dgridSF = new DataGridStyleFactory();
        DataSet dsDM = new DataSet();
        bool _bDiemChu = false;
        
        public frmNhapDiem()
        {
            // Sets the UI culture to VietNamese (VietNam) / English
            //if (GlobalVariable.WSInfo.Language == "Tiếng Việt")
            //    Thread.CurrentThread.CurrentUICulture = new CultureInfo("vi-VN");
            //else if (GlobalVariable.WSInfo.Language == "English")
            //    Thread.CurrentThread.CurrentUICulture = new CultureInfo("en");
 
            InitializeComponent();
        }


        private void cmdCapNhat_Click(object sender, EventArgs e)
        {
            DuyetRowState();

            if (!_bDiemChu)  //Luu diem so
                UpdateDataSet(dsDM);
            else
                UpdateDataSet_DiemChu(dsDM);

            LoadBangDiem();

            SetEditMode(false);
        }



        private void DuyetRowState()
        {
            DataTable dataTable = dsDM.Tables["BANGDIEM"];
            if (dataTable == null || dataTable.Rows.Count == 0)
                return;
            try
            {
                //dataTable.AcceptChanges();

                foreach (DataRow row in dataTable.Rows)
                    if (row["ID"] == DBNull.Value)
                    {
                        row.AcceptChanges();
                        row.SetAdded();
                    }
            }
            catch { }

            //Diem Chu
            DataTable dataTable_Chu = dsDM.Tables["BANGDIEM_DIEMCHU"];
            if (dataTable_Chu == null || dataTable_Chu.Rows.Count == 0)
                return;
            try
            {
                //dataTable.AcceptChanges();

                foreach (DataRow row in dataTable_Chu.Rows)
                    if (row["ID"] == DBNull.Value)
                    {
                        row.AcceptChanges();
                        row.SetAdded();
                    }
            }
            catch { }

        }


        public static void UpdateDataSet(DataSet ds)
        {
            SqlConnection cnn = new SqlConnection(GlobalVariable.WSInfo.ConnectionString);

            string sqlInsert, sqlUpdate, sqlDelete;
            sqlInsert = "INSERT INTO HOCSINH_LOP_KQHT(MaHocTap, MaMonKiemTra, MaHocKy, KTMieng_1, KTMieng_2, KTMieng_3, KTMieng_4, " +
                                              " KT15p_1, KT15p_2, KT15p_3, KT15p_4, KT15p_5, " +
                                              " KT1Tiet_1, KT1Tiet_2, KT1Tiet_3, KT1Tiet_4, KT1Tiet_5, KT1Tiet_6, " +
                                              " KTGiuaHK, KTHocKy " + 
                                              ") VALUES(@pMaHocTap, @pMaMonKiemTra, @pMaHocKy, @pKTMieng_1, @pKTMieng_2, @pKTMieng_3, @pKTMieng_4, "  +
                                              " @pKT15p_1, @pKT15p_2, @pKT15p_3, @pKT15p_4, @pKT15p_5, " +
                                              " @pKT1Tiet_1, @pKT1Tiet_2, @pKT1Tiet_3, @pKT1Tiet_4, @pKT1Tiet_5, @pKT1Tiet_6, " +
                                              " @pKTGiuaHK, @pKTHocKy " +
                                              ") ";

            sqlUpdate = "UPDATE HOCSINH_LOP_KQHT SET MaMonKiemTra=@pMaMonKiemTra, MaHocKy=@pMaHocKy, KTMieng_1=@pKTMieng_1, KTMieng_2=@pKTMieng_2, KTMieng_3=@pKTMieng_3, KTMieng_4=@pKTMieng_4, " +
                                                   " KT15p_1=@pKT15p_1, KT15p_2=@pKT15p_2, KT15p_3=@pKT15p_3, KT15p_4=@pKT15p_4, KT15p_5=@pKT15p_5, " +
                                                   " KT1Tiet_1=@pKT1Tiet_1, KT1Tiet_2=@pKT1Tiet_2, KT1Tiet_3=@pKT1Tiet_3, KT1Tiet_4=@pKT1Tiet_4, KT1Tiet_5=@pKT1Tiet_5, KT1Tiet_6=@pKT1Tiet_6,  " + 
                                                   " KTGiuaHK=@pKTGiuaHK, KTHocKy= @pKTHocKy " + 
                        " WHERE ID=@pID";

            sqlDelete = "DELETE FROM HOCSINH_LOP_KQHT WHERE ID=@pID";

            SqlParameter[] pInsert = new SqlParameter[20];
            SqlParameter[] pUpdate = new SqlParameter[20];
            SqlParameter[] pDelete = new SqlParameter[1];

            pInsert[0] = new SqlParameter("@pMaHocTap", SqlDbType.VarChar,  50, "MaHocTap");
            pInsert[1] = new SqlParameter("@pMaMonKiemTra", SqlDbType.VarChar, 10, "MaMonKiemTra");
            pInsert[2] = new SqlParameter("@pMaHocKy", SqlDbType.VarChar, 2, "MaHocKy");
            pInsert[3] = new SqlParameter("@pKTMieng_1", SqlDbType.Float, 18, "KTMieng_1");
            pInsert[4] = new SqlParameter("@pKTMieng_2", SqlDbType.Float, 18, "KTMieng_2");
            pInsert[5] = new SqlParameter("@pKTMieng_3", SqlDbType.Float, 18, "KTMieng_3");
            pInsert[6] = new SqlParameter("@pKTMieng_4", SqlDbType.Float, 18, "KTMieng_4");
            pInsert[7] = new SqlParameter("@pKT15p_1", SqlDbType.Float, 18, "KT15p_1");
            pInsert[8] = new SqlParameter("@pKT15p_2", SqlDbType.Float, 18, "KT15p_2");
            pInsert[9] = new SqlParameter("@pKT15p_3", SqlDbType.Float, 18, "KT15p_3");
            pInsert[10] = new SqlParameter("@pKT15p_4", SqlDbType.Float, 18, "KT15p_4");
            pInsert[11] = new SqlParameter("@pKT15p_5", SqlDbType.Float, 18, "KT15p_5");
            pInsert[12] = new SqlParameter("@pKT1Tiet_1", SqlDbType.Float, 18, "KT1Tiet_1");
            pInsert[13] = new SqlParameter("@pKT1Tiet_2", SqlDbType.Float, 18, "KT1Tiet_2");
            pInsert[14] = new SqlParameter("@pKT1Tiet_3", SqlDbType.Float, 18, "KT1Tiet_3");
            pInsert[15] = new SqlParameter("@pKT1Tiet_4", SqlDbType.Float, 18, "KT1Tiet_4");
            pInsert[16] = new SqlParameter("@pKT1Tiet_5", SqlDbType.Float, 18, "KT1Tiet_5");
            pInsert[17] = new SqlParameter("@pKT1Tiet_6", SqlDbType.Float, 18, "KT1Tiet_6");
            pInsert[18] = new SqlParameter("@pKTGiuaHK", SqlDbType.Float, 18, "KTGiuaHK");
            pInsert[19] = new SqlParameter("@pKTHocKy", SqlDbType.Float, 18, "KTHocKy");

            pUpdate[0] = new SqlParameter("@pMaMonKiemTra", SqlDbType.VarChar, 50, "MaMonKiemTra");
            pUpdate[1] = new SqlParameter("@pMaHocKy", SqlDbType.VarChar, 2, "MaHocKy");
            pUpdate[2] = new SqlParameter("@pKTMieng_1", SqlDbType.Float, 18, "KTMieng_1");
            pUpdate[3] = new SqlParameter("@pKTMieng_2", SqlDbType.Float, 18, "KTMieng_2");
            pUpdate[4] = new SqlParameter("@pKTMieng_3", SqlDbType.Float, 18, "KTMieng_3");
            pUpdate[5] = new SqlParameter("@pKTMieng_4", SqlDbType.Float, 18, "KTMieng_4");
            pUpdate[6] = new SqlParameter("@pKT15p_1", SqlDbType.Float, 18, "KT15p_1");
            pUpdate[7] = new SqlParameter("@pKT15p_2", SqlDbType.Float, 18, "KT15p_2");
            pUpdate[8] = new SqlParameter("@pKT15p_3", SqlDbType.Float, 18, "KT15p_3");
            pUpdate[9] = new SqlParameter("@pKT15p_4", SqlDbType.Float, 18, "KT15p_4");
            pUpdate[10] = new SqlParameter("@pKT15p_5", SqlDbType.Float, 18, "KT15p_5");
            pUpdate[11] = new SqlParameter("@pKT1Tiet_1", SqlDbType.Float, 18, "KT1Tiet_1");
            pUpdate[12] = new SqlParameter("@pKT1Tiet_2", SqlDbType.Float, 18, "KT1Tiet_2");
            pUpdate[13] = new SqlParameter("@pKT1Tiet_3", SqlDbType.Float, 18, "KT1Tiet_3");
            pUpdate[14] = new SqlParameter("@pKT1Tiet_4", SqlDbType.Float, 18, "KT1Tiet_4");
            pUpdate[15] = new SqlParameter("@pKT1Tiet_5", SqlDbType.Float, 18, "KT1Tiet_5");
            pUpdate[16] = new SqlParameter("@pKT1Tiet_6", SqlDbType.Float, 18, "KT1Tiet_6");
            pUpdate[17] = new SqlParameter("@pKTGiuaHK", SqlDbType.Float, 18, "KTGiuaHK");
            pUpdate[18] = new SqlParameter("@pKTHocKy", SqlDbType.Float, 18, "KTHocKy");
            pUpdate[19] = new SqlParameter("@pID", SqlDbType.Int, 18, "ID");

            pDelete[0] = new SqlParameter("@pID", SqlDbType.Int, 18, "ID");

            SqlCommand cmdInsert = new SqlCommand(sqlInsert,cnn);
            SqlCommand cmdUpdate = new SqlCommand(sqlUpdate,cnn);
            SqlCommand cmdDelete = new SqlCommand(sqlDelete,cnn);

            cmdInsert.Parameters.AddRange(pInsert);
            cmdUpdate.Parameters.AddRange(pUpdate);
            cmdDelete.Parameters.AddRange(pDelete);

            SqlDataAdapter da = new SqlDataAdapter();
            da.InsertCommand  = cmdInsert;
            da.UpdateCommand  = cmdUpdate;
            da.DeleteCommand  = cmdDelete;
            try
            {
                da.Update(ds, "BANGDIEM");
                ds.AcceptChanges();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        public static void UpdateDataSet_DiemChu(DataSet ds)
        {
            SqlConnection cnn = new SqlConnection(GlobalVariable.WSInfo.ConnectionString);

            string sqlInsert, sqlUpdate, sqlDelete;
            sqlInsert = "INSERT INTO HOCSINH_LOP_KQHT_CHU(MaHocTap, MaMonKiemTra, MaHocKy, KTMieng_1, KTMieng_2, KTMieng_3, KTMieng_4, " +
                                              " KT15p_1, KT15p_2, KT15p_3, KT15p_4, KT15p_5, " +
                                              " KT1Tiet_1, KT1Tiet_2, KT1Tiet_3, KT1Tiet_4, KT1Tiet_5, KT1Tiet_6, " +
                                              " KTGiuaHK, KTHocKy " +
                                              ") VALUES(@pMaHocTap, @pMaMonKiemTra, @pMaHocKy, @pKTMieng_1, @pKTMieng_2, @pKTMieng_3, @pKTMieng_4, " +
                                              " @pKT15p_1, @pKT15p_2, @pKT15p_3, @pKT15p_4, @pKT15p_5, " +
                                              " @pKT1Tiet_1, @pKT1Tiet_2, @pKT1Tiet_3, @pKT1Tiet_4, @pKT1Tiet_5, @pKT1Tiet_6, " +
                                              " @pKTGiuaHK, @pKTHocKy " +
                                              ") ";

            sqlUpdate = "UPDATE HOCSINH_LOP_KQHT_CHU SET MaMonKiemTra=@pMaMonKiemTra, MaHocKy=@pMaHocKy, KTMieng_1=@pKTMieng_1, KTMieng_2=@pKTMieng_2, KTMieng_3=@pKTMieng_3, KTMieng_4=@pKTMieng_4, " +
                                                   " KT15p_1=@pKT15p_1, KT15p_2=@pKT15p_2, KT15p_3=@pKT15p_3, KT15p_4=@pKT15p_4, KT15p_5=@pKT15p_5, " +
                                                   " KT1Tiet_1=@pKT1Tiet_1, KT1Tiet_2=@pKT1Tiet_2, KT1Tiet_3=@pKT1Tiet_3, KT1Tiet_4=@pKT1Tiet_4, KT1Tiet_5=@pKT1Tiet_5, KT1Tiet_6=@pKT1Tiet_6,  " +
                                                   " KTGiuaHK=@pKTGiuaHK, KTHocKy= @pKTHocKy " +
                        " WHERE ID=@pID";

            sqlDelete = "DELETE FROM HOCSINH_LOP_KQHT_CHU WHERE ID=@pID";

            SqlParameter[] pInsert = new SqlParameter[20];
            SqlParameter[] pUpdate = new SqlParameter[20];
            SqlParameter[] pDelete = new SqlParameter[1];

            pInsert[0] = new SqlParameter("@pMaHocTap", SqlDbType.VarChar, 50, "MaHocTap");
            pInsert[1] = new SqlParameter("@pMaMonKiemTra", SqlDbType.VarChar, 10, "MaMonKiemTra");
            pInsert[2] = new SqlParameter("@pMaHocKy", SqlDbType.VarChar, 2, "MaHocKy");
            pInsert[3] = new SqlParameter("@pKTMieng_1", SqlDbType.NVarChar, 50, "KTMieng_1");
            pInsert[4] = new SqlParameter("@pKTMieng_2", SqlDbType.NVarChar, 50, "KTMieng_2");
            pInsert[5] = new SqlParameter("@pKTMieng_3", SqlDbType.NVarChar, 50, "KTMieng_3");
            pInsert[6] = new SqlParameter("@pKTMieng_4", SqlDbType.NVarChar, 50, "KTMieng_4");
            pInsert[7] = new SqlParameter("@pKT15p_1", SqlDbType.NVarChar, 50, "KT15p_1");
            pInsert[8] = new SqlParameter("@pKT15p_2", SqlDbType.NVarChar, 50, "KT15p_2");
            pInsert[9] = new SqlParameter("@pKT15p_3", SqlDbType.NVarChar, 50, "KT15p_3");
            pInsert[10] = new SqlParameter("@pKT15p_4", SqlDbType.NVarChar, 50, "KT15p_4");
            pInsert[11] = new SqlParameter("@pKT15p_5", SqlDbType.NVarChar, 50, "KT15p_5");
            pInsert[12] = new SqlParameter("@pKT1Tiet_1", SqlDbType.NVarChar, 50, "KT1Tiet_1");
            pInsert[13] = new SqlParameter("@pKT1Tiet_2", SqlDbType.NVarChar, 50, "KT1Tiet_2");
            pInsert[14] = new SqlParameter("@pKT1Tiet_3", SqlDbType.NVarChar, 50, "KT1Tiet_3");
            pInsert[15] = new SqlParameter("@pKT1Tiet_4", SqlDbType.NVarChar, 50, "KT1Tiet_4");
            pInsert[16] = new SqlParameter("@pKT1Tiet_5", SqlDbType.NVarChar, 50, "KT1Tiet_5");
            pInsert[17] = new SqlParameter("@pKT1Tiet_6", SqlDbType.NVarChar, 50, "KT1Tiet_6");
            pInsert[18] = new SqlParameter("@pKTGiuaHK", SqlDbType.NVarChar, 50, "KTGiuaHK");
            pInsert[19] = new SqlParameter("@pKTHocKy", SqlDbType.NVarChar, 50, "KTHocKy");

            pUpdate[0] = new SqlParameter("@pMaMonKiemTra", SqlDbType.VarChar, 50, "MaMonKiemTra");
            pUpdate[1] = new SqlParameter("@pMaHocKy", SqlDbType.VarChar, 2, "MaHocKy");
            pUpdate[2] = new SqlParameter("@pKTMieng_1", SqlDbType.NVarChar, 50, "KTMieng_1");
            pUpdate[3] = new SqlParameter("@pKTMieng_2", SqlDbType.NVarChar, 50, "KTMieng_2");
            pUpdate[4] = new SqlParameter("@pKTMieng_3", SqlDbType.NVarChar, 50, "KTMieng_3");
            pUpdate[5] = new SqlParameter("@pKTMieng_4", SqlDbType.NVarChar, 50, "KTMieng_4");
            pUpdate[6] = new SqlParameter("@pKT15p_1", SqlDbType.NVarChar, 50, "KT15p_1");
            pUpdate[7] = new SqlParameter("@pKT15p_2", SqlDbType.NVarChar, 50, "KT15p_2");
            pUpdate[8] = new SqlParameter("@pKT15p_3", SqlDbType.NVarChar, 50, "KT15p_3");
            pUpdate[9] = new SqlParameter("@pKT15p_4", SqlDbType.NVarChar, 50, "KT15p_4");
            pUpdate[10] = new SqlParameter("@pKT15p_5", SqlDbType.NVarChar, 50, "KT15p_5");
            pUpdate[11] = new SqlParameter("@pKT1Tiet_1", SqlDbType.NVarChar, 50, "KT1Tiet_1");
            pUpdate[12] = new SqlParameter("@pKT1Tiet_2", SqlDbType.NVarChar, 50, "KT1Tiet_2");
            pUpdate[13] = new SqlParameter("@pKT1Tiet_3", SqlDbType.NVarChar, 50, "KT1Tiet_3");
            pUpdate[14] = new SqlParameter("@pKT1Tiet_4", SqlDbType.NVarChar, 50, "KT1Tiet_4");
            pUpdate[15] = new SqlParameter("@pKT1Tiet_5", SqlDbType.NVarChar, 50, "KT1Tiet_5");
            pUpdate[16] = new SqlParameter("@pKT1Tiet_6", SqlDbType.NVarChar, 50, "KT1Tiet_6");
            pUpdate[17] = new SqlParameter("@pKTGiuaHK", SqlDbType.NVarChar, 50, "KTGiuaHK");
            pUpdate[18] = new SqlParameter("@pKTHocKy", SqlDbType.NVarChar, 50, "KTHocKy");
            pUpdate[19] = new SqlParameter("@pID", SqlDbType.Int, 18, "ID");

            pDelete[0] = new SqlParameter("@pID", SqlDbType.Int, 18, "ID");

            SqlCommand cmdInsert = new SqlCommand(sqlInsert, cnn);
            SqlCommand cmdUpdate = new SqlCommand(sqlUpdate, cnn);
            SqlCommand cmdDelete = new SqlCommand(sqlDelete, cnn);

            cmdInsert.Parameters.AddRange(pInsert);
            cmdUpdate.Parameters.AddRange(pUpdate);
            cmdDelete.Parameters.AddRange(pDelete);

            SqlDataAdapter da = new SqlDataAdapter();
            da.InsertCommand = cmdInsert;
            da.UpdateCommand = cmdUpdate;
            da.DeleteCommand = cmdDelete;
            try
            {
                da.Update(ds, "BANGDIEM_DIEMCHU");
                ds.AcceptChanges();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void GetData()
        {
            //if (selectCommand == "") return;

            if (cboHocKy.SelectedIndex == -1 || cboLop.SelectedIndex == -1 || cboMon.SelectedIndex == -1)
                return;

            try
            {
                SqlConnection cnn = new SqlConnection(GlobalVariable.WSInfo.ConnectionString);
                
                SqlCommand sqlCom = new SqlCommand("sp_Giaovu_LoadBangDiem", cnn);
                sqlCom.CommandType = CommandType.StoredProcedure;
                
                sqlCom.Parameters.Add(new SqlParameter("@pMaLop", SqlDbType.VarChar)).Value = cboLop.SelectedValue.ToString();
                sqlCom.Parameters.Add(new SqlParameter("@pMaHocKy", SqlDbType.VarChar)).Value = cboHocKy.SelectedValue.ToString() ;
                sqlCom.Parameters.Add(new SqlParameter("@pMaMonHoc", SqlDbType.VarChar)).Value =  cboMon.SelectedValue.ToString() ;

                SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlCom);

                if (dsDM.Tables["BANGDIEM"] != null)
                        dsDM.Tables["BANGDIEM"].Clear();
                
                dataAdapter.Fill(dsDM, "BANGDIEM");
                //table.Locale = System.Globalization.CultureInfo.InvariantCulture;
                bindingSource1.DataSource = dsDM.Tables["BANGDIEM"];
                
                SetEditMode(false);
                dgridDiem.Focus();
                if(chkNhap1Cot.Checked) chkNhap1Cot.Checked = false;

            }
            catch (SqlException ex)
            {
                MessageBox.Show("Error: \n" + ex.Message);
            }
        }


        private void GetData_DiemChu()
        {
            if (cboHocKy.SelectedIndex == -1 || cboLop.SelectedIndex == -1 || cboMon.SelectedIndex == -1)
                return;

            try
            {
                SqlConnection cnn = new SqlConnection(GlobalVariable.WSInfo.ConnectionString);

                SqlCommand sqlCom = new SqlCommand("sp_Giaovu_LoadBangDiem_DiemChu", cnn);
                sqlCom.CommandType = CommandType.StoredProcedure;

                sqlCom.Parameters.Add(new SqlParameter("@pMaLop", SqlDbType.VarChar)).Value = cboLop.SelectedValue.ToString();
                sqlCom.Parameters.Add(new SqlParameter("@pMaHocKy", SqlDbType.VarChar)).Value = cboHocKy.SelectedValue.ToString();
                sqlCom.Parameters.Add(new SqlParameter("@pMaMonHoc", SqlDbType.VarChar)).Value = cboMon.SelectedValue.ToString();

                SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlCom);

                if (dsDM.Tables["BANGDIEM_DIEMCHU"] != null)
                    dsDM.Tables["BANGDIEM_DIEMCHU"].Clear();

                dataAdapter.Fill(dsDM, "BANGDIEM_DIEMCHU");
                //table.Locale = System.Globalization.CultureInfo.InvariantCulture;
                bindingSource_DiemChu.DataSource = dsDM.Tables["BANGDIEM_DIEMCHU"];

                SetEditMode(false);
                dgridDiemChu.Focus();
                if (chkNhap1Cot.Checked) chkNhap1Cot.Checked = false;

            }
            catch (SqlException ex)
            {
                MessageBox.Show("Error: \n" + ex.Message);
            }
        }


        private void frmNhapDiem_Load(object sender, EventArgs e)
        {
            InitComboBoxFromDM();
            
            dgridDiem.Dock = DockStyle.Fill;
            dgridDiemChu.Dock = DockStyle.Fill;

            try
            {
                if (GlobalVariable.WSInfo.WorkingDate.Month >= 1 && GlobalVariable.WSInfo.WorkingDate.Month < 8)
                    cboHocKy.SelectedValue = 2;
            }
            catch { };

            // Bind the DataGridView to the BindingSource
            // and load the data from the database.
            dgridDiem.DataSource = bindingSource1;
            dgridDiemChu.DataSource = bindingSource_DiemChu;

            LoadBangDiem();
        }


        private void frmNhapDiem_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {

            /*
            //if (e.Column.ColumnName.ToUpper() == strMaKey.ToUpper() ) return;   //Khong co load de tim du lieu cho truong co ten la <MAKEY>

            string Ma = "";
            string DanhMuc = "";
            string Ten = "";

            if (e.Column.ColumnName.ToUpper().Substring(0, 2) == "MA")
            {
                Ma = e.Column.ColumnName.ToUpper();
                DanhMuc = e.Column.ColumnName.ToUpper().Replace("MA", "DM_");
                Ten = e.Column.ColumnName.ToUpper().Replace("MA", "TEN");
                //Khong co trong danh muc la hien list data
            }

            //Cac truong hop can liet ke (khong thuoc kieu MAxx, DM_xxx)
            if (e.Column.ColumnName.ToUpper() == "MAHOCTAP")
            {
                Ma = e.Column.ColumnName.ToUpper();
                DanhMuc = "View_DanhSachHocVien";
                Ten = "HoTenHV";
            }
            if (e.Column.ColumnName.ToUpper() == "ENQUIRYNUMBER")
            {
                Ma = e.Column.ColumnName.ToUpper();
                DanhMuc = " (Select distinct EnquiryNumber, Holot + ' ' + Ten as HoTenHV from Enquiry) as Data ";
                Ten = "HoTenHV";
            }
            if (e.Column.ColumnName.ToUpper() == "INVOICENUMBER")
            {
                Ma = e.Column.ColumnName.ToUpper();
                DanhMuc = " (Select distinct InvoiceNumber, HoTenHV from View_Invoice) as Data ";
                Ten = "HoTenHV";
            }

            if (e.Column.ColumnName.ToUpper() == "ENROLLNUMBER")
            {
                Ma = e.Column.ColumnName.ToUpper();
                DanhMuc = " (Select distinct  InvoiceNumber as EnrollNumber, HoTenHV from View_Invoice) as Data ";
                Ten = "HoTenHV";
            }

            if (Ma == "") return;

            //Read only cot Ten
            if (Ten != "")
                try
                {
                    //dg.TableStyles[0].GridColumnStyles[Ten].ReadOnly = true;
                }
                catch { }

            try  //Neu ko co se xuong catch
            {
                string str = CNCSoft.EData.SQLHelper.ExecuteScalar(GlobalVariable.WSInfo.ConnectionString,
                            "SELECT " + Ma + " FROM " + DanhMuc + " WHERE " + Ma + " = '" + e.Row[e.Column.ColumnName] + "'").ToString();
            }
            catch (Exception ex)
            {
                //Can xu ly them truong hop khong co DanhMuc (do ngo nhan ten MA...)
                if (ex.Message.IndexOf("'" + DanhMuc + "'") < 0)  //Bao loi lien quan den Danh Muc (Invalid Object name <DM>). Khong co DanhMuc thi thoi, ko load data list lam gi
                {
                   // e.Row[e.Column.ColumnName] = LoadListData("SELECT * FROM " + DanhMuc);
                    try
                    {
                        e.Row[Ten] = CNCSoft.EData.SQLHelper.ExecuteScalar(GlobalVariable.WSInfo.ConnectionString,
                                "SELECT " + Ten + " FROM " + DanhMuc + " WHERE " + Ma + " = '" + e.Row[e.Column.ColumnName] + "'").ToString();
                    }
                    catch { }

                    return;
                }
            }
             */
        }


        private void InitComboBoxFromDM()
        {
            dataAdapter = new SqlDataAdapter("SELECT * FROM DM_NIENHOC", GlobalVariable.WSInfo.ConnectionString);
            dataAdapter.Fill(dsDM, "DM_NienHoc");

            dataAdapter = new SqlDataAdapter("SELECT * FROM DM_LOP WHERE MaNienHoc= '" + cboNienHoc.SelectedValue + "'", GlobalVariable.WSInfo.ConnectionString);
            dataAdapter.Fill(dsDM, "DM_NienHoc");

            dataAdapter = new SqlDataAdapter("SELECT * FROM DM_LOP WHERE MaNienHoc = '" + cboNienHoc.SelectedValue + "'", GlobalVariable.WSInfo.ConnectionString);
            dataAdapter.Fill(dsDM, "DM_Lop");

            dataAdapter = new SqlDataAdapter("SELECT * FROM DM_MONKIEMTRA", GlobalVariable.WSInfo.ConnectionString);
            dataAdapter.Fill(dsDM, "DM_MonKiemTra");

            dataAdapter = new SqlDataAdapter("SELECT * FROM DM_HOCKY", GlobalVariable.WSInfo.ConnectionString);
            dataAdapter.Fill(dsDM, "DM_HocKy");

            cboNienHoc.DataSource = dsDM.Tables["DM_NienHoc"];
            cboNienHoc.ValueMember = "MaNienHoc";
            cboNienHoc.DisplayMember = "TenNienHoc";
            cboNienHoc.SelectedValue = GlobalVariable.WSInfo.getAppProperty("MaNienHocDefault");

            cboLop.DataSource = dsDM.Tables["DM_Lop"];
            cboLop.ValueMember = "MaLop";
            cboLop.DisplayMember = "TenLop";

            cboMon.DataSource = dsDM.Tables["DM_MonKiemTra"];
            cboMon.ValueMember = "MaMonKiemTra";
            cboMon.DisplayMember = "TenMonKiemTra";

            cboHocKy.DataSource = dsDM.Tables["DM_HocKy"];
            cboHocKy.ValueMember = "MaHocKy";
            cboHocKy.DisplayMember = "TenMonHoc";
        }
        

        private void cboNienHoc_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                string strCS = "";
                if (chkCS1.Checked) strCS = "'1'";
                if (chkCS2.Checked) strCS = "'2'";
                if (chkCS1.Checked && chkCS2.Checked) strCS = "'1', '2'";

                string strSQLDMLOP = "SELECT * FROM DM_LOP WHERE MaNienHoc = '" + cboNienHoc.SelectedValue + "'"  +
                                     " AND MaCoSo IN (" + strCS + ")  order by MaKhoi desc, STT  ";
                
                dsDM.Tables["DM_Lop"].Clear()  ;
                dataAdapter = new SqlDataAdapter(strSQLDMLOP, GlobalVariable.WSInfo.ConnectionString);
                dataAdapter.Fill(dsDM, "DM_Lop");

                LoadBangDiem();
                
            }
            catch { }

        }


        private void LoadBangDiem()
        {
            /*
            string strSELECT = "select  M.MaHocTap, M.MaLop, M.MaHocSinh, HoLot, Ten, ID, " +
                    "'" + cboMon.SelectedValue + "' as MaMonKiemTra, '" + cboHocKy.SelectedValue + "' as MaHocKy, " +
                    "KTMieng_1, KTMieng_2, KTMieng_3, KTMieng_4, " +
                    "KT15p_1, KT15p_2, KT15p_3, KT15p_4, KT15p_5, " +
                    "KT1Tiet_1, KT1Tiet_2, KT1Tiet_3, KT1Tiet_4, KT1Tiet_5, " +
                    "KTGiuaHK, KTHocKy " +
                    "from HOCSINH_LOP M " +
                    "left join (SELECT * FROM HOCSINH_LOP_KQHT WHERE MaMonKiemTra = '" + cboMon.SelectedValue + "' AND MaHocKy = '" + cboHocKy.SelectedValue + "') " + 
                    "as D on M.MaHocTap = D.MaHocTap " +
                    "join HOCSINH on M.MaHocSinh = HOCSINH.MaHocSinh " +
                    "join DM_LOP on M.MaLop = DM_LOP.MaLop " +
                    "where M.MaLop = '" + cboLop.SelectedValue + "' " +
                    "order by Ten " ;
           */
            //GetData(strSELECT);

            if (cboMon.SelectedIndex >= 0)
            {
                if (!_bDiemChu) 
                {
                    dgridDiemChu.Visible = false;
                    dgridDiem.Visible = true;
                    GetData();
                }
                else
                {
                    dgridDiemChu.Visible = true;
                    dgridDiem.Visible = false ;
                    GetData_DiemChu();
                }
            }

            
        }

        private void cboMon_SelectedIndexChanged(object sender, EventArgs e)
        {
            //MessageBox.Show(dsDM.Tables["DM_MonKiemTra"].Rows[cboMon.SelectedIndex]["DiemChu"].ToString());
            //if (cboMon.SelectedValue.ToString() == "TDTT")
            if (Convert.ToBoolean(dsDM.Tables["DM_MonKiemTra"].Rows[cboMon.SelectedIndex]["DiemChu"]))
                _bDiemChu = true;
            else
                _bDiemChu = false;

            LoadBangDiem();
        }

        private void cboHocKy_SelectedIndexChanged(object sender, EventArgs e)
        {
                LoadBangDiem();
        }

        private void cboLop_SelectedIndexChanged(object sender, EventArgs e)
        {
                LoadBangDiem();
        }

        private void chkMieng_CheckedChanged(object sender, EventArgs e)
        {
            bandedGridView_DayDu.Bands["KTMieng"].Visible = chkMieng.Checked;
            bandedGridView_DiemChu.Bands["KTMieng_DiemChu"].Visible = chkMieng.Checked;
        }

        private void chk1Tiet_CheckedChanged(object sender, EventArgs e)
        {
            bandedGridView_DayDu.Bands["KT1Tiet"].Visible = chk1Tiet.Checked;
            bandedGridView_DiemChu.Bands["KT1Tiet_DiemChu"].Visible = chk1Tiet.Checked;
        }

        private void chk15Phut_CheckedChanged(object sender, EventArgs e)
        {
            bandedGridView_DayDu.Bands["KT15p"].Visible = chk15Phut.Checked;
            bandedGridView_DiemChu.Bands["KT15p_DiemChu"].Visible = chk15Phut.Checked;
        }

        private void chkHocKy_CheckedChanged(object sender, EventArgs e)
        {
            bandedGridView_DayDu.Bands["HocKy"].Visible = chkHocKy.Checked;
            bandedGridView_DiemChu.Bands["HocKy_DiemChu"].Visible = chkHocKy.Checked;
        }

        private void chkKT_TongHopTuNoiCu_CheckedChanged(object sender, EventArgs e)
        {
            bandedGridView_DayDu.Bands["gridBand_TongHop"].Visible = chkKT_TongHopTuNoiCu.Checked;
            bandedGridView_DiemChu.Bands["gridBand_TongHop_DiemChu"].Visible = chkKT_TongHopTuNoiCu.Checked;
        }

        private void bandedGridView_DayDu_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e)
        {
            //if (e.Value == null ||  e.Value.GetType().Name != System.TypeCode.Decimal.ToString()) 
            if (e.Value == null || e.Value.ToString() == "")
            {
                e.Value = null;
                SetEditMode(true);
                return;
            }

            try
            {
                Double val = Convert.ToDouble(e.Value);
                if (val > 100 || val < 0)
                {
                    e.Valid = false;
                    e.ErrorText = "Điểm không hợp lệ. ";
                    return;
                }
                if (val > 10)
                {
                    //Chia cho 10 de thuan tien cho viec nhap lieu (ko can dau phay)
                    e.Value = Convert.ToDecimal(e.Value) / 10;
                }

                SetEditMode(true);
            }
            catch
            {
            }
        }

        private void SetEditMode(bool bEdit)
        {
            cboNienHoc.Enabled = !bEdit;
            cboLop.Enabled = !bEdit;
            cboHocKy.Enabled = !bEdit;
            cboMon.Enabled = !bEdit;

            cmdBoQua.Enabled = bEdit;
            cmdCapNhat.Enabled = bEdit;
        }

        private void cmdBoQua_Click(object sender, EventArgs e)
        {
            LoadBangDiem();
            SetEditMode(false);
        }

        private void chkFilterRow_CheckedChanged(object sender, EventArgs e)
        {
            bandedGridView_DayDu.OptionsView.ShowAutoFilterRow = chkFilterRow.Checked;
            bandedGridView_DiemChu.OptionsView.ShowAutoFilterRow = chkFilterRow.Checked;
        }

        private void chkHOAhoten_CheckedChanged(object sender, EventArgs e)
        {
            try
            {

                if (chkHOAhoten.Checked)
                {
                    bandedGridView_DayDu.Columns["HoLot"].ColumnEdit = repositoryItemTextChuHOA;
                    bandedGridView_DayDu.Columns["Ten"].ColumnEdit = repositoryItemTextChuHOA;
                    bandedGridView_DiemChu.Columns["HoLot"].ColumnEdit = repositoryItemTextChuHOA;
                    bandedGridView_DiemChu.Columns["Ten"].ColumnEdit = repositoryItemTextChuHOA;
                }
                else
                {
                    bandedGridView_DayDu.Columns["HoLot"].ColumnEdit = repositoryItemTextChuKHONGHOA;
                    bandedGridView_DayDu.Columns["Ten"].ColumnEdit = repositoryItemTextChuKHONGHOA;
                    bandedGridView_DiemChu.Columns["HoLot"].ColumnEdit = repositoryItemTextChuKHONGHOA;
                    bandedGridView_DiemChu.Columns["Ten"].ColumnEdit = repositoryItemTextChuKHONGHOA;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bandedGridView_DayDu_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            
        }

        private void chkCS1_CheckedChanged(object sender, EventArgs e)
        {
            cboNienHoc_SelectedIndexChanged(sender, e);
        }

        private void chkCS2_CheckedChanged(object sender, EventArgs e)
        {
            cboNienHoc_SelectedIndexChanged(sender, e);
        }

        private void chkNhap1Cot_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (!_bDiemChu)
                {
                    if (!chkNhap1Cot.Checked)
                    {
                        for (int i = 1; i < bandedGridView_DayDu.Columns.Count; i++)
                            bandedGridView_DayDu.Columns[i].OptionsColumn.AllowFocus = true;
                        return;
                    }
                    //MessageBox.Show(bandedGridView_DayDu.FocusedColumn.Name);
                    for (int i = 1; i < bandedGridView_DayDu.Columns.Count; i++)
                    {
                        //bandedGridView_DayDu.Columns[i].OptionsColumn.AllowFocus = !chkNhap1Cot.Checked  ;
                        if (bandedGridView_DayDu.Columns[i].Name == bandedGridView_DayDu.FocusedColumn.Name)
                            bandedGridView_DayDu.Columns[i].OptionsColumn.AllowFocus = true;
                        else
                            bandedGridView_DayDu.Columns[i].OptionsColumn.AllowFocus = false;
                    }

                    dgridDiem.Focus();
                }

                else
                {
                    if (!chkNhap1Cot.Checked)
                    {
                        for (int i = 1; i < bandedGridView_DiemChu.Columns.Count; i++)
                            bandedGridView_DiemChu.Columns[i].OptionsColumn.AllowFocus = true;
                        return;
                    }
                    //MessageBox.Show(bandedGridView_DayDu.FocusedColumn.Name);
                    for (int i = 1; i < bandedGridView_DiemChu.Columns.Count; i++)
                    {
                        //bandedGridView_DayDu.Columns[i].OptionsColumn.AllowFocus = !chkNhap1Cot.Checked  ;
                        if (bandedGridView_DiemChu.Columns[i].Name == bandedGridView_DiemChu.FocusedColumn.Name)
                            bandedGridView_DiemChu.Columns[i].OptionsColumn.AllowFocus = true;
                        else
                            bandedGridView_DiemChu.Columns[i].OptionsColumn.AllowFocus = false;
                    }

                    dgridDiemChu.Focus();
                }


            } 
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }

        private void cmdInBangDiem_Click(object sender, EventArgs e)
        {
            try
            {

                cmdInBangDiem.Enabled = false;

                //Load report
                ReportDocument rpt = new ReportDocument();
                rpt.Load(Application.StartupPath + "\\Report\\Report_Giaovu_BangDiem_Mon.rpt");

                //Set connection
                PublicFunction.SetDBLogonForReport(rpt);

                //Set parameter
                PublicFunction.SetParameter(rpt, "@pMaLop", cboLop.SelectedValue );
                PublicFunction.SetParameter(rpt, "@pMaMonKiemTra", cboMon.SelectedValue);
                PublicFunction.SetParameter(rpt, "@pMaHocKy", cboHocKy.SelectedValue);
                //PublicFunction.SetParameter(rpt, "pNguoiLapBieu", GlobalVariable.WSInfo.UserName);
                PublicFunction.SetParameter(rpt, "@pFieldGroup", "");
                PublicFunction.SetParameter(rpt, "pMoRongDong", false);

                //View report
                frmPrintPreview frmPP = new frmPrintPreview(rpt);
                frmPP.ShowDialog();
                frmPP.Dispose();

                rpt.Dispose();
                cmdInBangDiem.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bandedGridView_DayDu_MouseWheel(object sender, MouseEventArgs e)
        {
             
        }

        private void bandedGridView_DayDu_ShowingEditor(object sender, CancelEventArgs e)
        {
            
            TextEdit edit = (sender as BaseView).ActiveEditor as TextEdit;
            if (edit != null)
                edit.Spin += new DevExpress.XtraEditors.Controls.SpinEventHandler(edit_Spin);
        }

        void edit_Spin(object sender, DevExpress.XtraEditors.Controls.SpinEventArgs e)
        {
            e.Handled = false;
        }

        private void bandedGridView_DiemChu_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e)
        {
            try
            {
                if (e.Value.ToString()  == "")
                    e.Value = null;

                string val = e.Value.ToString().ToUpper();
                if (val == null) return;

                if (!((val == "Đ" || val == "CĐ" || val == "D" || val == "0" || val == "1")))
                {
                    e.Valid = false;
                    e.ErrorText = "Chỉ có Đạt (Đ/D/1) hoặc chưa đạt (CĐ/C/0) ";
                    return;
                }

                if (val == "D" || val == "1")
                    e.Value = "Đ";
                if (val == "0")
                    e.Value = "CĐ";

                SetEditMode(true);
            }
            catch
            {
            }
        }

        

        

    }
}
